package com.octopus.media.fuwu;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketServer extends Service {

    private final int JoinThreadTime = 1000;
    private SocketSendThread socketSendThread;
    private SocketReadThread socketReadThread;
    private boolean isrun = true;

    private static final String HOST = "192.168.1.6";
    private static final int PORT = 5132;
    private InputStream inReadr;
    private Socket socket;

    @SuppressLint("StaticFieldLeak")
    @Override
    public void onCreate() {
        super.onCreate();

        AsyncTask asyncTask = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] objects) {
                initSocket();
                return "start";
            }
        };
        asyncTask.execute();

        isrun = true;
        socketSendThread = new SocketSendThread(SocketServer.this);
        socketSendThread.start();
        socketReadThread = new SocketReadThread(SocketServer.this);
        socketReadThread.start();
        Log.i("Socket","MonitoringThread start");
    }

    public void initSocket() {
        try {
            socket = new Socket(HOST, PORT);
            socket.setKeepAlive(true);
            socket.setSoTimeout(JoinThreadTime*60);
            inReadr = socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void stopSocket(){
        try {
            if (inReadr != null)
                inReadr.close();
            if (socket != null)
                socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            socket = null;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        try {
            stopSocket();
            isrun = false;
            socketSendThread.join(JoinThreadTime);
            socketReadThread.join(JoinThreadTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i("Socket","MonitoringThread join");
        super.onDestroy();
    }

    public class SocketSendThread extends Thread{

        private Context context;

        public SocketSendThread(Context context){
            this.context = context;
            Log.i("Socket","ScoketSendThread build");
        }

        @Override
        public void run() {
            super.run();
            Log.i("Socket","Socket w run");
            while (isrun){
                Log.i("Socket","Socket w loop");
                try {
                    Thread.sleep(  10000);
                    sendMsg();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private void sendMsg(){
            try {
                if (socket == null){
                    initSocket();
                }else{
                    if (socket.isConnected()) {
                        String msg = "pi !!!";
                        socket.getOutputStream().write(msg.getBytes());
                        socket.getOutputStream().flush();
                        Log.i("Socket", ("socketService: printWriter send"));
                    }else{
                        socket.connect(new InetSocketAddress(HOST, PORT), 2000);
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
                stopSocket();
            }
        }
    }

    public class SocketReadThread extends Thread {

        private Context context;

        public SocketReadThread(Context context) {
            this.context = context;
            Log.i("Socket", "SocketReadThread build");
        }

        @Override
        public void run() {
            super.run();
            Log.i("Socket", "Socket r run");
            while (isrun) {
                Log.i("Socket", "Socket r loop");
                try {
                    Thread.sleep(500);
                    readMsg();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private void readMsg() {
            try {
                if (socket == null){
                    initSocket();
                }else{
                    if (inReadr != null  && socket.isConnected()) {
                        Log.i("Socket", ("socketService: running read"));
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = inReadr.read(buffer)) != -1) {
                            String data = new String(buffer, 0, len);
                            Log.i("Socket", "socketService---------------------------------------------:" + data);
                            if (!data.equals("")){
                                Intent intent = new Intent("com.media.listFile");
                                context.sendBroadcast(intent);
                            }
                        }
                    }else{
                        socket.connect(new InetSocketAddress(HOST, PORT), 2000);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                stopSocket();
            }
        }

    }
}
